package imchat

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"sync"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	ws "mall/service/backend/common/websocket"
	"mall/service/user/api/internal/svc"
	"mall/service/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ImChatLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 即时聊天
func NewImChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImChatLogic {
	return &ImChatLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImChatLogic) ImChat(req *types.ChatReq, w http.ResponseWriter, r *http.Request) (resp *types.BaseMsgResp, err error) {
	if req.UserID == nil || *req.UserID == 0 {
		return nil, fmt.Errorf("invalid user id")
	}
	userId := *req.UserID
	client := ws.NewChatClient(userId, w, r)
	wg := &sync.WaitGroup{}
	wg.Add(2)
	go client.WritePump(wg)
	go client.ReadPump(wg)
	if userId > 10000 {
		content := &ws.Message{
			MsgType:  pointy.GetPointer(globalkey.ChatMessageTypePrivate),
			FriendId: pointy.GetPointer(strconv.FormatUint(userId, 10)),
			Msg:      pointy.GetPointer("欢迎来到独角嗅！"),
		}
		client.SendMsg(content)
	}
	wg.Wait()

	return &types.BaseMsgResp{}, nil
}
